<template>
  <el-dialog
    title="导出数据"
    :model-value="modelValue"
    @update:model-value="$emit('update:modelValue', $event)"
    width="500px"
  >
    <div class="export-options">
      <h4>选择导出格式</h4>
      
      <el-radio-group v-model="selectedFormat" class="format-options">
        <el-radio label="excel-basic" class="format-option">
          <div class="format-content">
            <div class="format-icon">📊</div>
            <div class="format-info">
              <div class="format-title">基础Excel</div>
              <div class="format-desc">包含任务列表和统计信息</div>
            </div>
          </div>
        </el-radio>
        
        <el-radio label="excel-timeline" class="format-option">
          <div class="format-content">
            <div class="format-icon">📅</div>
            <div class="format-info">
              <div class="format-title">时间线Excel</div>
              <div class="format-desc">按时间顺序排列的任务时间线</div>
            </div>
          </div>
        </el-radio>
        
        <el-radio label="excel-report" class="format-option">
          <div class="format-content">
            <div class="format-icon">📋</div>
            <div class="format-info">
              <div class="format-title">项目报告</div>
              <div class="format-desc">完整的项目报告，包含多维度统计</div>
            </div>
          </div>
        </el-radio>
        
        <el-radio label="json" class="format-option">
          <div class="format-content">
            <div class="format-icon">📄</div>
            <div class="format-info">
              <div class="format-title">JSON数据</div>
              <div class="format-desc">原始数据格式，便于数据迁移</div>
            </div>
          </div>
        </el-radio>
      </el-radio-group>
      
      <div class="export-settings" v-if="selectedFormat.startsWith('excel')">
        <h4>导出设置</h4>
        
        <el-form :model="exportSettings" label-width="100px">
          <el-form-item label="文件名">
            <el-input 
              v-model="exportSettings.filename" 
              placeholder="请输入文件名（可选）"
              clearable
            />
          </el-form-item>
          
          <el-form-item label="包含内容">
            <el-checkbox-group v-model="exportSettings.includeContent">
              <el-checkbox label="tasks">任务列表</el-checkbox>
              <el-checkbox label="statistics">统计信息</el-checkbox>
              <el-checkbox label="timeline">时间轴信息</el-checkbox>
            </el-checkbox-group>
          </el-form-item>
          
          <el-form-item label="数据范围">
            <el-radio-group v-model="exportSettings.dataRange">
              <el-radio label="all">全部任务</el-radio>
              <el-radio label="visible">仅显示任务</el-radio>
              <el-radio label="filtered">按筛选条件</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
      </div>
      
      <div class="export-preview" v-if="selectedFormat.startsWith('excel')">
        <h4>预览信息</h4>
        <div class="preview-content">
          <div class="preview-item">
            <span class="preview-label">任务数量:</span>
            <span class="preview-value">{{ getPreviewTaskCount() }}</span>
          </div>
          <div class="preview-item">
            <span class="preview-label">时间范围:</span>
            <span class="preview-value">{{ getPreviewTimeRange() }}</span>
          </div>
          <div class="preview-item">
            <span class="preview-label">文件大小:</span>
            <span class="preview-value">{{ getPreviewFileSize() }}</span>
          </div>
        </div>
      </div>
    </div>
    
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="$emit('update:modelValue', false)">取消</el-button>
        <el-button 
          type="primary" 
          @click="handleExport"
          :loading="isExporting"
        >
          {{ isExporting ? '导出中...' : '开始导出' }}
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script>
import { ref, reactive, computed, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { 
  exportToExcel, 
  exportTimelineToExcel, 
  exportProjectReportToExcel 
} from '../utils/excelExport.js'
import dayjs from 'dayjs'

export default {
  name: 'ExportDialog',
  props: {
    modelValue: {
      type: Boolean,
      default: false
    },
    tasks: {
      type: Array,
      default: () => []
    },
    filteredTasks: {
      type: Array,
      default: () => []
    },
    timeline: {
      type: Object,
      default: () => ({})
    },
    statistics: {
      type: Object,
      default: () => ({})
    }
  },
  emits: ['update:modelValue', 'export-success'],
  setup(props, { emit }) {
    
    const selectedFormat = ref('excel-basic')
    const isExporting = ref(false)
    
    const exportSettings = reactive({
      filename: '',
      includeContent: ['tasks', 'statistics'],
      dataRange: 'all'
    })
    
    // 监听格式变化，更新默认设置
    watch(selectedFormat, (newFormat) => {
      switch (newFormat) {
        case 'excel-basic':
          exportSettings.includeContent = ['tasks', 'statistics']
          exportSettings.dataRange = 'all'
          break
        case 'excel-timeline':
          exportSettings.includeContent = ['tasks', 'timeline']
          exportSettings.dataRange = 'all'
          break
        case 'excel-report':
          exportSettings.includeContent = ['tasks', 'statistics', 'timeline']
          exportSettings.dataRange = 'all'
          break
        case 'json':
          exportSettings.includeContent = ['tasks', 'statistics', 'timeline']
          exportSettings.dataRange = 'all'
          break
      }
    })
    
    // 获取要导出的任务数据
    const getExportTasks = () => {
      switch (exportSettings.dataRange) {
        case 'visible':
          return props.filteredTasks
        case 'filtered':
          return props.filteredTasks
        case 'all':
        default:
          return props.tasks
      }
    }
    
    // 获取预览任务数量
    const getPreviewTaskCount = () => {
      const tasks = getExportTasks()
      return tasks.length
    }
    
    // 获取预览时间范围
    const getPreviewTimeRange = () => {
      const tasks = getExportTasks()
      if (tasks.length === 0) return '无数据'
      
      const startDates = tasks.map(t => dayjs(t.startDate))
      const endDates = tasks.map(t => dayjs(t.endDate))
      
      const minStart = dayjs.min(startDates)
      const maxEnd = dayjs.max(endDates)
      
      return `${minStart.format('YYYY-MM-DD')} 至 ${maxEnd.format('YYYY-MM-DD')}`
    }
    
    // 获取预览文件大小
    const getPreviewFileSize = () => {
      const tasks = getExportTasks()
      const estimatedSize = tasks.length * 200 + 1000 // 粗略估算
      
      if (estimatedSize < 1024) {
        return `${estimatedSize} B`
      } else if (estimatedSize < 1024 * 1024) {
        return `${(estimatedSize / 1024).toFixed(1)} KB`
      } else {
        return `${(estimatedSize / (1024 * 1024)).toFixed(1)} MB`
      }
    }
    
    // 处理导出
    const handleExport = async () => {
      if (isExporting.value) return
      
      isExporting.value = true
      
      try {
        const tasks = getExportTasks()
        const timeline = {
          start: props.timeline.start || dayjs().format('YYYY-MM-DD'),
          end: props.timeline.end || dayjs().format('YYYY-MM-DD')
        }
        
        let filename = null
        if (exportSettings.filename.trim()) {
          filename = exportSettings.filename.trim()
          if (!filename.endsWith('.xlsx') && !filename.endsWith('.json')) {
            filename += selectedFormat.startsWith('excel') ? '.xlsx' : '.json'
          }
        }
        
        let result
        switch (selectedFormat.value) {
          case 'excel-basic':
            result = exportToExcel(tasks, timeline, props.statistics, filename)
            break
          case 'excel-timeline':
            result = exportTimelineToExcel(tasks, filename)
            break
          case 'excel-report':
            result = exportProjectReportToExcel(tasks, timeline, props.statistics, filename)
            break
          case 'json':
            result = exportToJson(tasks, timeline, props.statistics, filename)
            break
          default:
            throw new Error('不支持的导出格式')
        }
        
        ElMessage.success(`导出成功: ${result}`)
        emit('export-success', { format: selectedFormat.value, filename: result })
        emit('update:modelValue', false)
        
      } catch (error) {
        console.error('导出失败:', error)
        ElMessage.error(`导出失败: ${error.message}`)
      } finally {
        isExporting.value = false
      }
    }
    
    // 导出JSON格式
    const exportToJson = (tasks, timeline, statistics, filename = null) => {
      const data = {
        tasks: tasks,
        timeline: timeline,
        statistics: statistics,
        exportTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
        exportSettings: exportSettings
      }
      
      const blob = new Blob([JSON.stringify(data, null, 2)], { 
        type: 'application/json' 
      })
      const url = URL.createObjectURL(blob)
      const a = document.createElement('a')
      a.href = url
      
      const defaultFilename = `gantt-data_${dayjs().format('YYYY-MM-DD_HH-mm-ss')}.json`
      a.download = filename || defaultFilename
      
      document.body.appendChild(a)
      a.click()
      document.body.removeChild(a)
      URL.revokeObjectURL(url)
      
      return a.download
    }
    
    return {
      selectedFormat,
      exportSettings,
      isExporting,
      getPreviewTaskCount,
      getPreviewTimeRange,
      getPreviewFileSize,
      handleExport
    }
  }
}
</script>

<style scoped>
.export-options {
  padding: 20px 0;
}

.export-options h4 {
  margin: 0 0 15px 0;
  color: #303133;
  font-size: 16px;
}

.format-options {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.format-option {
  width: 100%;
  margin-right: 0;
}

.format-option :deep(.el-radio__label) {
  width: 100%;
  padding-left: 0;
}

.format-content {
  display: flex;
  align-items: center;
  padding: 12px;
  border: 1px solid #DCDFE6;
  border-radius: 6px;
  transition: all 0.3s;
}

.format-option :deep(.el-radio__input.is-checked) + .el-radio__label .format-content {
  border-color: #409EFF;
  background-color: #F0F9FF;
}

.format-icon {
  font-size: 24px;
  margin-right: 12px;
  width: 40px;
  text-align: center;
}

.format-info {
  flex: 1;
}

.format-title {
  font-weight: 600;
  color: #303133;
  margin-bottom: 4px;
}

.format-desc {
  font-size: 12px;
  color: #909399;
  line-height: 1.4;
}

.export-settings {
  margin-top: 24px;
  padding-top: 20px;
  border-top: 1px solid #EBEEF5;
}

.export-settings h4 {
  margin: 0 0 15px 0;
  color: #303133;
  font-size: 16px;
}

.export-preview {
  margin-top: 20px;
  padding: 15px;
  background-color: #F5F7FA;
  border-radius: 6px;
}

.export-preview h4 {
  margin: 0 0 12px 0;
  color: #303133;
  font-size: 14px;
}

.preview-content {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.preview-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.preview-label {
  color: #606266;
  font-size: 13px;
}

.preview-value {
  color: #303133;
  font-weight: 500;
  font-size: 13px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}
</style> 